package com.liujit.common.utils;

import cn.hutool.core.io.IoUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @description: 请求上下文工具类
 * @author: liujun
 * @create: 2020/12/31 4:52 下午
 **/
@Slf4j
public class ReqUtil {

    /**
     * 获取request
     *
     * @return
     */
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        if (requestAttributes == null) {
            return null;
        }
        HttpServletRequest request = requestAttributes.getRequest();
        return request;
    }

    /**
     * 获取response
     *
     * @return
     */
    public static HttpServletResponse getResponse() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        HttpServletResponse response = requestAttributes.getResponse();
        return response;
    }

    /**
     * 获取request body
     *
     * @param request
     * @return
     */
    @SneakyThrows
    public static String getRequestBody(HttpServletRequest request) {
        return IoUtil.read(request.getInputStream(), StandardCharsets.UTF_8);
    }

    /**
     * 获取request 请求参数
     *
     * @param paramStr
     * @return
     */
    public static String getRequestParam(String paramStr) {
        return getRequest().getParameter(paramStr);
    }

    /**
     * 获取header
     *
     * @param headerKey
     * @return
     */
    public static String getHeader(String headerKey) {
        return getRequest().getHeader(headerKey);
    }

}
